<template>
  <div class="rs422-config-form">
    <a-card :title="formTitle" style="width: 100%">
      <!-- 加载状态 -->
      <a-alert v-if="loading" message="正在加载配置文件..." type="info" show-icon style="margin-bottom: 16px" />

      <!-- 错误提示 -->
      <a-alert
        v-if="error"
        :message="error"
        type="error"
        show-icon
        style="margin-bottom: 16px"
        closable
        @close="error = ''"
      />

      <!-- 成功提示 -->
      <a-alert
        v-if="successMessage"
        :message="successMessage"
        type="success"
        show-icon
        style="margin-bottom: 16px"
        closable
        @close="successMessage = ''"
      />

      <!-- 表单内容 -->
      <a-form
        v-if="!loading && Object.keys(parameters).length > 0"
        :form="form"
        @submit="handleSubmit"
        :label-col="{ span: 10 }"
        :wrapper-col="{ span: 14 }"
      >
        <!-- 动态生成表单字段 -->
        <template v-for="(paramConfig, paramName) in parameters">
          <a-form-item :key="paramName" :label="paramConfig.Description">
            <!-- 数字输入框 -->
            <a-input-number
              v-if="paramConfig.Type === 'int'"
              v-decorator="[
                paramName,
                {
                  initialValue: paramConfig.Value,
                  rules: validationRules[paramName]
                }
              ]"
              :min="paramConfig.Range ? paramConfig.Range[0] : undefined"
              :max="paramConfig.Range ? paramConfig.Range[1] : undefined"
              :placeholder="placeholders[paramName]"
              style="width: 100%"
            />

            <!-- 文本输入框 -->
            <a-input
              v-else
              v-decorator="[
                paramName,
                {
                  initialValue: paramConfig.Value,
                  rules: validationRules[paramName]
                }
              ]"
              :placeholder="placeholders[paramName]"
            />
          </a-form-item>
        </template>

        <!-- 提交按钮 -->
        <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
          <a-button
            type="primary"
            html-type="submit"
            :loading="submitting"
            :disabled="Object.keys(parameters).length === 0"
          >
            提交配置1
          </a-button>
          <a-button style="margin-left: 10px" @click="handleReset" :disabled="Object.keys(parameters).length === 0">
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <!-- 空状态 -->
      <a-empty v-else-if="!loading && Object.keys(parameters).length === 0" description="未找到可配置的参数" />
    </a-card>
  </div>
</template>

<script>
import {
  loadYamlParameters,
  generateValidationRules,
  generatePlaceholders,
  loadFullYaml,
  updateYamlValues,
  convertToYamlString,
  createYamlBlob,
  uploadYamlFile
} from '@/utils/yamlLoader'

import { httpAction, getAction } from '@/api/manage'
export default {
  name: 'Rs422ConfigForm',
  props: {
    // YAML文件地址
    yamlFileUrl: {
      type: String,
      required: true
    },
    // 表单标题
    formTitle: {
      type: String,
      default: 'RS422配置参数'
    }
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'rs422_config' }),
      parameters: {},
      originalYamlData: null, // 新增：保存原始YAML数据
      validationRules: {},
      placeholders: {},
      loading: false,
      error: '',
      successMessage: '',
      submitting: false,
      originalYamlData: null // 存储原始YAML数据
    }
  },
  mounted() {
    this.loadParametersFromYaml()
  },
  watch: {
    // 监听YAML文件地址变化，重新加载
    yamlFileUrl: {
      handler(newUrl) {
        if (newUrl) {
          this.loadParametersFromYaml()
        }
      },
      immediate: false
    }
  },
  methods: {
    async loadParametersFromYaml() {
      this.loading = true
      this.error = ''
      this.parameters = {}
      this.originalYamlData = null // 重置原始数据

      try {
        // 新增：加载完整的YAML数据
        const fullYaml = await loadFullYaml(this.yamlFileUrl)
        this.originalYamlData = fullYaml.data

        // 加载YAML参数
        this.parameters = await loadYamlParameters(this.yamlFileUrl)
        console.log(this.yamlFileUrl, 'url============this.yamlFileUrl=')

        // 生成验证规则
        this.validationRules = generateValidationRules(this.parameters)

        // 生成placeholder
        this.placeholders = generatePlaceholders(this.parameters)

        console.log('参数加载完成:', this.parameters)
        console.log('验证规则:', this.validationRules)
        console.log('Placeholders:', this.placeholders)
        console.log('原始YAML数据:', this.originalYamlData) // 新增日志
      } catch (error) {
        console.error('加载参数失败:', error)
        this.error = error.message || '加载配置文件失败'
        this.parameters = {}
      } finally {
        this.loading = false
      }
    },

    // 处理表单提交
    // 处理表单提交
    handleSubmit(e) {
      e.preventDefault()

      this.form.validateFields((err, values) => {
        if (!err) {
          this.submitting = true

          console.log('提交的表单值:', values)

          // 新增：构建保存数据
          const saveData = {
            content: this.generateUpdatedYamlContent(values),
            filePath: this.yamlFileUrl
          }

          console.log('保存数据11111111:', saveData)

          // 调用保存接口
          httpAction('/sys/common/saveFileContent', saveData, 'POST')
            .then(res => {
              if (res.success) {
                this.$message.success(res.message)
                // 触发提交成功事件
                this.$emit('submit-success', values)
              } else {
                this.$message.warning(res.message)
              }
            })
            .catch(error => {
              console.error('保存配置失败:', error)
              this.$message.error('保存配置失败: ' + (error.message || '未知错误'))
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    },
    // 生成更新后的YAML内容
    generateUpdatedYamlContent(formValues) {
      if (!this.originalYamlData) {
        throw new Error('原始YAML数据未加载')
      }

      // 更新YAML数据中的值
      const updatedData = updateYamlValues(this.originalYamlData, formValues)

      // 转换为YAML字符串
      return convertToYamlString(updatedData)
    },
    // 重置表单
    handleReset() {
      this.form.resetFields()
      this.successMessage = ''
      this.error = ''
      this.$message.info('表单已重置')
    },

    // 重新加载参数（外部可调用）
    reloadParameters() {
      this.loadParametersFromYaml()
    },

    // 获取类型显示名称
    getTypeDisplayName(type) {
      const typeMap = {
        int: '整数',
        string: '字符串',
        boolean: '布尔值',
        float: '浮点数'
      }
      return typeMap[type] || type
    }
  }
}
</script>

<style scoped>
.rs422-config-form {
  max-width: 600px;
  margin: 20px auto;
  padding: 0 20px;
}

.range-hint {
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

.type-hint {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}
</style>
